from src.vobjects.playlist import Playlist
from src.vobjects.torrent import Torrent
from src.vobjects.channel import Channel
from src.vobjects.video import Video
from src.plugin import Plugin

import json

import requests

class Api:

    def __init__(self, config):
        self.host = f'{config.InstanceUrl}/api/v1.0/'
        
        try:
            requests.get(self.host)
        except:
            print(f"Error: Can't connect to {config.InstanceUrl}! (Enable your local server or change server url)")
            exit(1)

    def get_plugins(self):
        url = self.host + 'getPlugins'
        resp = requests.get(url)
        
        items = list()
        jsitems = resp.json()
        for jsitem in jsitems:
            item = Plugin.from_json(jsitem)
            items.append(item)

        return items
    
    def get_plugin_items(self, id, params): 
        url = self.host + 'getPluginItems/' + str(id)
        resp = requests.get(url, {
            "params" : json.dumps(params),
        })  

        jsitems = resp.json()

        items = list()
        for jsitem in jsitems:
            if jsitem['type'] == 'video':
                item = Video()
            elif jsitem['type'] == 'playlist':
                item = Playlist()
            elif jsitem['type'] == 'channel':
                item = Channel()
            elif jsitem['type'] == 'torrent':
                items.append(Torrent.from_json(jsitem).to_item())
                continue
            else: continue
            item = item.from_json(jsitem).to_item()
            items.append(item)

        return items

    def insert_video_to_history(self, video):
        url = self.host + 'insertVideoToHistory'
        requests.post(url, json=video.to_json())

       


